<template>
	<div class="edit-frame flex" :key="resetKey">
		<div class="edit-input">
			<p class="title" v-if="showPreview">
				<img class="title-icon" src="@rc/assets/images/icon-edit.png" alt="">
				题目编辑区域:
			</p>
			<div class="base">
				<p class="top">
					<span class="title">基本信息</span>
					<el-button v-if="basicPropList.length>4" type="text" @click="toggle('base')">{{ basicMax===5?'收起':"补充更多" }}</el-button>
				</p>
				<ve-content>
					<select-groups-base
						ref="baseRef"
						teacher-avlstatus="Y"
						label-width="75px"
						:prop-list="basicPropList"
						:disable-prop-list="disableBasicPropList"
						:rules-prop-list="['projectId','subjectId']"
						:max="basicMax"
						:chapter-multiple="true"
						:knowledge-multiple="true"
						:basic-info="initData.basicInfo"
						@change="onBasicChange"
					/>
				</ve-content>
			</div>
			<div class="tag" v-show="isShowTagForm">
				<p class="top">
					<span class="title">标签信息</span>
					<el-button type="text" @click="toggle('tag')">{{ tagMax===7?'收起':"补充更多" }}</el-button>
				</p>
				<ve-content>
					<select-groups-tag
						ref="tagRef"
						label-width="75px"
						:disable-prop-list="disableTagPropList"
						:tag-info="initData.tagInfo"
						:area-multiple="true"
						:init-value-prop-list="initValuePropList"
						:max="tagMax"
						@change="onTagChange"
					/>
				</ve-content>
			</div>
			<div class="question">
				<p class="top">
					<span class="title">试题信息</span>
				</p>
				<ve-content>
					<question-form
						ref="questionFormRef"
						:parent-type="parentType"
						:type="type"
						:init-data="initData.questionInfo"
						:basic-info="basicInfo"
						:tag-info="tagInfo"
						@change="onQuestionChange"
					/>
				</ve-content>
			</div>
			<div class="edit-btns flex ai-center jc-center">
				<el-button @click="resetForm">重置</el-button>
				<!-- 1.新增或编辑大题中的子题时不展示 2.单独编辑子题展示-->
				<el-button
					v-if="!parentType || showPreview"
					type="primary"
					:loading="isLoading"
					@click="onSubmit(()=>{})"
				>
					提交
				</el-button>
				<!-- 新增大题中的子题时不展示 -->
				<el-button
					v-if="!parentType && type==='add'"
					:loading="isLoading"
					class="theme_font_color theme-border-color"
					@click="onSubmitNextAdd"
				>
					提交并添加下一题
				</el-button>
				<!-- 1.新增或编辑大题中的子题时不展示  2.单独编辑子题展示-->
				<el-button
					v-if="(!parentType ||showPreview) && type==='edit' "
					class="theme_font_color theme-border-color"
					:loading="isLoading"
					@click="onSubmitNextEdit"
				>
					提交并编辑下一题
				</el-button>
				<!-- 新增或编辑大题中的子题时展示 -->
				<el-button
					v-if="parentType && !showPreview"
					type="primary"
					:loading="isLoading"
					@click="save"
				>
					保存
				</el-button>
			</div>
		</div>
		<ve-trans-div v-if="showPreview" class="trans" />
		<!-- 预览 -->
		<div class="edit-preview" v-if="showPreview">
			<p class="title"><img class="title-icon" src="@rc/assets/images/icon-preview.png" alt="">题目预览:</p>
			<div class="preview">
				<question-show
					:data="questionInfo"
				/>
			</div>
		</div>
		<repeat-process-single-dialog
			:show.sync="isShowProcessDialog"
			:question="processQuestion"
			:repeat-resource-id="processRepeatResourceId"
			@success="handleProcessSuccess"
			:is-saving="isWriting"
			:is-show-tool="isShowProcessTool"
			:op-origin="processToolLabel"
			:question-resource-id="processQuestionResourceId"
			:will-replace-question="processWillReplaceQuestion"
		/>
	</div>
</template>
<script>
	import SelectGroupsBase from "../select-groups-base/index.vue";
	import SelectGroupsTag from "../select-groups-tag/index.vue";
	import QuestionForm from "./components/question-form/index.vue";
    import questionApi  from "@rc/apis/rc/question.mjs";
    import RepeatProcessSingleDialog from "./components/repeat-process-single-dialog.vue";

	export default {
        name:'edit-frame',
		props: {
			parentType: {
				//添加或编辑组合题中子题时需要传递 对应的大题类型
				type: String,
				default: ""
			},
            parentResourceId: {//小题对应的大题id，仅从编辑小题时使用
                type: String,
				default: ""
            },
			questionData: {//初始化数据
				type: Object,
				default: () => {}
			},
            type:{//编辑或者新增
                type: String,
				default: ""
            },
            showPreview:{//编辑或者新增
                type: Boolean,
				default: true
            }
		},
		components: {
			SelectGroupsBase,
			SelectGroupsTag,
			QuestionForm,
            QuestionShow:() => import("@rc/pages/components/question-base/question-show/index.vue"),
            RepeatProcessSingleDialog,
		},
        computed:{
            //基础信息禁用的表单项
            disableBasicPropList(){
                return this.parentType? ['projectId','subjectId']:[];
            },
            //基础信息显示的表单项
            basicPropList(){
                //编辑和新增试题显示内容相同
                // if(this.type==='edit' && this.combinedType.includes(this.questionInfo.questionType)) {
                //     return ['projectId','subjectId'];
                // } else {
                    return ['projectId','subjectId','chapter', 'knowledgePoint','questionDeveloperId'];
                // }
            },
            //是否显示标签属性
            isShowTagForm(){
                // return !(this.type==='edit' && this.combinedType.includes(this.questionInfo.questionType));
                return true;
            },
            //禁用的标签属性
            disableTagPropList(){
                return this.parentType? ['试题年份','所属地区','试题分类','适用范围']:[];
            },
            //新增试题时默认的标签属性
            initValuePropList(){
                return this.type==='add'&&!this.parentType ?['试题年份', '所属地区', '试题分类', '适用范围']:[];
            },
            isShowProcessTool() {
                return  this.type === 'add';
            },
            processToolLabel() {
                return  this.type === 'add' ? '新增' : '编辑';
            },
        },
        watch:{
            questionData:{
                deep:true,
                immediate:true,
                handler(val) {
                    if(val) {
                        const question = JSON.parse(JSON.stringify(val));
                        let questionInfo = JSON.parse(JSON.stringify(val));
                        delete questionInfo.basicInfo;
                        delete questionInfo.tagInfo;
                        this.initData = {
                            basicInfo:question.basicInfo,
                            tagInfo:question.tagInfo,
                            questionInfo
                        };

                    }
                }
            }
        },
		data() {
			return {
				initData: {},//初始化数据
				basicMax: 4, //基本属性默认展示
				tagMax: 4, //标签属性默认展示
				questionInfo: {}, //题目信息
				basicInfo: {}, //基本属性信息
				tagInfo: {}, //标签属性信息
                resetKey:0,
                isLoading:false,
                combinedType: ["A", "CF", "L", "C"],//组合题题型
                timer: null, //防抖定时器
                isShowProcessDialog: false,
                processQuestion: null,
                processRepeatResourceId: undefined,
                processQuestionResourceId: undefined,
                isWriting: false,
                processWillReplaceQuestion: [],
			};
		},
		methods: {
			toggle(type) {
				if (type === "base") {
					this.basicMax = this.basicMax === 4 ? 5 : 4;
				} else if (type === "tag") {
					this.tagMax = this.tagMax === 4 ? -1 : 4;
				}
			},
            onBasicChange(basicInfo) {
				this.basicInfo = basicInfo;
			},
			onTagChange(tagInfo) {
				this.tagInfo = tagInfo;
			},
			onQuestionChange(question) {
				this.questionInfo = question;
			},
            addQuestion(params, callback) {
                //提取所有的图片路径
                let imgList = this.getImgList([params]);
                console.log(imgList);
                questionApi.addQuestion({
                    data: {
                        ...params,
                        filePathList:Array.from(new Set(imgList))
                    },
                    success: ({ repeatResourceId, questionRepeatMessageList = [] }) => {
                        console.warn('addQuestion- repeatResourceId', repeatResourceId, params);
                        if (repeatResourceId) {
                            if (params.smallQuestionList) {
                                params.smallQuestionList.forEach((item) => {
                                    this.$set(item, 'applicableYear', params.applicableYear);
                                    this.$set(item, 'areaList', params.areaList);
                                });
                            }
                            console.warn('addQuestion-params', params);
                            this.processQuestion = params;
                            this.processRepeatResourceId = repeatResourceId;
                            this.isShowProcessDialog = true;
                            this.processWillReplaceQuestion = [];
                            this.processQuestionResourceId = '';
                        } else if (questionRepeatMessageList.length > 0) {
                            this.$alert(questionRepeatMessageList.join(), "重复试题提示");
                        } else {
                            this.$message.success('试题录入成功');
                            callback && callback();
                        }
                    },
                    complete: () => {
                            this.isLoading = false;
                        }
                    });
            },
            updateResource(params,callback){
                this.isLoading = true;
                 let imgList = this.getImgList([params]);
                questionApi.updateResource({
                    data: {
                        ...params,
                        filePathList:Array.from(new Set(imgList))
                    },
                    success: ({ operatedResourceId, repeatResourceId, questionRepeatMessageList = [] }) => {
                        console.warn('updateResource', operatedResourceId, repeatResourceId);
                        if (repeatResourceId) {
                            if (params.smallQuestionList) {
                                params.smallQuestionList.forEach((item) => {
                                    this.$set(item, 'applicableYear', params.applicableYear);
                                    this.$set(item, 'areaList', params.areaList);
                                });
                            }
                            console.warn('updateResource-params', params);
                            this.processQuestion = params;
                            this.processRepeatResourceId = repeatResourceId;
                            this.isShowProcessDialog = true;
                            this.processWillReplaceQuestion = [...params.smallQuestionList];
                            this.processQuestionResourceId = '';
                        } else if (questionRepeatMessageList.length > 0) {
                            this.$alert(questionRepeatMessageList.join(), "重复试题提示");
                        } else {
                            this.$message.success('试题编辑成功');
                            callback && callback();
                        }
                    },
                    complete: () => {
                            this.isLoading = false;
                        }
                    });
            },
            //编辑小题
            updateSmallResource(params,callback){
                this.isLoading = true;
                 let imgList = this.getImgList([params]);
                questionApi.updateSmallResource({
                    data: {
                        ...params,
                        filePathList:Array.from(new Set(imgList))
                    },
                    success: ({ operatedResourceId, repeatResourceId, questionRepeatMessageList = [] }) => {
                        console.warn('updateSmallResource', operatedResourceId, repeatResourceId);
                        if (repeatResourceId) {
                            this.processQuestion = null;
                            this.processQuestionResourceId = operatedResourceId;
                            this.processRepeatResourceId = repeatResourceId;
                            this.isShowProcessDialog = true;
                            this.processWillReplaceQuestion = [params];
                        } else if (questionRepeatMessageList <= 0) {
                            this.$message.success('试题编辑成功');
                            callback && callback();
                        } else {
                            this.$alert(questionRepeatMessageList.join(), "重复试题提示");
                        }
                    },
                    complete: () => {
                            this.isLoading = false;
                        }
                    });
            },
            /**
             * 处理独立题型和大题传参格式
             * 不包含小题的题型：章节、知识点、标签信息...都传
             *  大题：不传章节、知识点、标签信息
            */
            getQuestion(question) {
                const {
                    projectId,
                    projectName,
                    subjectId,
                    subjectName,
                    chapterList,
                    questionDeveloperId,
                    questionDeveloperName,
                    knowledgeList
                } = this.$refs.baseRef.api_result();
                const {applicableYear,areaList,labelList} = this.$refs.tagRef.api_result();
                question = {
                    ...question,
                    projectId:projectId.length?projectId[projectId.length-1]:'',
                    projectName,
                    subjectId,
                    subjectName,
                    chapterList,
                    questionDeveloperId,
                    questionDeveloperName,
                    knowledgeList,
                    applicableYear,
                    labelList: labelList?labelList.filter(label=>label.labelDetailId):[],
                    areaList
                };
                // 题型不传递optionList 案例分析和完型填空和听力题
                if(['A','CF','L'].includes(question.questionType)){
                    delete question.optionList;
                }
                // 仅独立题型传递视频/音频解析字段
                if(!this.combinedType.includes(question.questionType)){
                    if(question.questionVideoPathList){
                        let questionVideoPathList = question.questionVideoPathList.filter(item=>item.questionAvPath);
                        if(questionVideoPathList.length===0){
                            delete question.questionVideoPathList;
                        } else {
                            question.questionVideoPathList = questionVideoPathList.map(item=>{
                                return {
                                    questionAvPath:item.questionAvPath,
                                    questionAvSeq:item.questionAvSeq
                                };
                            });
                        }
                    }
                    //音频解析
                    if(question.questionAudioPathList){
                        let questionAudioPathList = question.questionAudioPathList.filter(item=>item.questionAvPath);
                        if(questionAudioPathList.length===0){
                            delete question.questionAudioPathList;
                        } else {
                            question.questionAudioPathList = questionAudioPathList.map(item=>{
                                return {
                                    questionAvPath:item.questionAvPath,
                                    questionAvSeq:item.questionAvSeq
                                };
                            });
                        }
                    }
                } else {
                    delete question.questionVideoPathList;
                    delete question.questionAudioPathList;
                }

                // 除简答题外其他题型也返回了这些字段，前端去掉类型判断  ---特殊处理 如果智能阅卷关键词/关键词得分权重为空则不传这两个字段
                let props = ['questionKeywords','questionScoreWeight'];
                props.forEach((prop)=>{
                    if(question[prop] === '' || question[prop] === null || question[prop] === undefined){
                        delete question[prop];
                    }
                });
                delete question.answerList;
                return question;
            },
            replaceImg(content){
                let imgList = [];
                content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, function (match, capture) {
                    imgList.push(capture); // capture图片地址 img标签中src内容   match // img标签整体
                });
                return imgList;
            },
            //获取上传的图片
            getImgList(list){
                let imgList = [];
                list.forEach(question=>{
                    for(let key in question) {
                        if(key==='optionList' && question.optionList) {
                            question.optionList.forEach(option=>{
                                const imgs = this.replaceImg(option.answerOption);
                                imgList.push(...imgs);
                            });
                        }
                        if(key==='questionAnswerParse'||key==='questionTitle'){
                            const imgs = this.replaceImg(question[key]);
                            imgList.push(...imgs);
                        }
                        if (this.combinedType.includes(question.questionType)){
                            const imgs = this.getImgList(question.smallQuestionList);
                            imgList.push(...imgs);
                        }
                    }
                });
                return imgList;
            },
            //函数防抖
            debounce(callback, wait=0) {
                if (!this.timer) {
                    callback();
                    this.timer = setTimeout(() => {
                        clearTimeout(this.timer);
                        this.timer = null;
                    }, wait);
                }
            },
            //点击提交按钮
            async submit(callback){
                // 校验必填项
                const validateBase = await this.$refs.baseRef.api_validateField();
                const questionBase = await this.$refs.questionFormRef.api_validate();
                if(!questionBase || !validateBase){ //校验通过
                    return;
                }
                let question = JSON.parse(JSON.stringify(this.questionInfo));
                question = this.getQuestion(question);
                if(this.combinedType.includes(question.questionType)){
                    let smallQuestionList = [];
                    question.smallQuestionList.forEach((smallQuestion)=>{
                        //小题：不传年份、地区、项目、科目
                        delete smallQuestion.smallQuestionList;
                        delete smallQuestion.projectId;
                        delete smallQuestion.projectName;
                        delete smallQuestion.subjectId;
                        delete smallQuestion.subjectName;
                        delete smallQuestion.areaList;
                        delete smallQuestion.applicableYear;
                        delete smallQuestion.areaIds;
                        delete smallQuestion.chapterIds;
                        smallQuestion.labelList = smallQuestion.labelList ? smallQuestion.labelList.filter(label => label.labelDetailId) : [];
                        smallQuestion.labelList.forEach((litem) => {
                            const l = question.labelList.find((qlitem) => litem.labelDetailId === qlitem.labelDetailId);
                            if (l) {
                                this.$set(litem, 'labelDetailName', l.labelDetailName);
                                this.$set(litem, 'labelName', l.labelName);
                            }
                        });
                        smallQuestionList.push(smallQuestion);
                    });
                    question.smallQuestionList = smallQuestionList;

                    //大题：不传章节、知识点、标签信息
                    delete question.chapterList;
                    delete question.knowledgeList;
                    delete question.labelList;
                }
                if (this.type === 'add') {
                    this.addQuestion(question, callback);
                }
                if(this.type==='edit'){
                    if(this.parentType) {// 编辑小题
                        if(this.parentResourceId){
                            question.parentResourceId = this.parentResourceId;
                        }
                        this.updateSmallResource(question,callback);
                    } else {// 编辑独立题型和大题
                        this.updateResource(question,callback);
                    }

                }
            },
            onSubmit(){
                this.debounce(() => {
                    this.opType =  this.type === 'add' ? 'SubmitAdd' : 'SubmitEdit';
                    this.submit(() => {
                        nlapp.TabManager.closeBack(`/rc/questions/list`);
                    });
                }, 1000);
            },
            //提交并添加下一题
            onSubmitNextAdd(){
                this.debounce(()=>{
                    this.opType = 'SubmitNextAdd';
                    this.submit(()=>{
                        this.addNextQuestion();
                    });
                },1000);
            },
            addNextQuestion() {
                this.resetKey++;
                //自动继承上一题的项目、科目、章节信息
                const {
                    projectId,
                    projectName,
                    subjectId,
                    subjectName,
                    chapterList} = this.basicInfo;
                this.initData.basicInfo = {
                    projectId,
                    projectName,
                    subjectId,
                    subjectName,
                    chapterIds:chapterList?chapterList.map(chapter=>chapter.chapterId):[],
                    chapterList:chapterList||[]
                };
            },
            //提交并编辑下一题
            onSubmitNextEdit(){
                this.debounce(()=>{
                    this.opType = 'SubmitNextEdit';
                    this.submit(()=>{
                        this.$emit('edit-next');
                    });
                },1000);
            },
            // 子题保存
            async save(){
                const validateBase = await this.$refs.baseRef.api_validateField();
                const questionBase = await this.$refs.questionFormRef.api_validate();
                if(!questionBase || !validateBase){ //校验通过
                    return;
                }
                let questionInfo = this.getQuestion(this.questionInfo);
                delete questionInfo.areaIds;
                this.$emit("sub-save",questionInfo);
            },
            resetForm(){
                this.resetKey++;
            },
            handleProcessSuccess(type = '') {
                console.warn('handleProcessSuccess', type, this.opType);
                if (this.opType === 'SubmitEdit') {
                    return;
                } else if (this.opType === 'SubmitNextEdit') {
                    return;
                }
                if (type === 'abandon') {
                    if (this.opType === 'SubmitAdd') {
                        nlapp.TabManager.closeBack('/rc/questions/list');
                    } else if (this.opType === 'SubmitNextAdd') {
                        this.addNextQuestion();
                    }
                } else if (type === 'all' || type === 'base') {
                    this.isWriting = true;
                    this.rewriteSubmit(type).then(() => {
                        this.isShowProcessDialog = false;
                        if (this.opType === 'SubmitAdd') {
                            nlapp.TabManager.closeBack('/rc/questions/list');
                        } else if (this.opType === 'SubmitNextAdd') {
                            this.addNextQuestion();
                        }
                    }).finally(() => {
                        this.isWriting = false;
                    });
                }
            },
            rewriteSubmit(type) {
                this.processQuestion.repeatResourceId = this.processRepeatResourceId;
                const questionTypeList = [this.processQuestion.questionType];
                const questionList = [this.processQuestion];
                const getQuestion = (question) => {
                    delete question.isError;
                    delete question.errorInfo;
                    const {
                        projectId,
                        projectName,
                        subjectId,
                        subjectName,
                        chapterList,
                        questionDeveloperId,
                        questionDeveloperName,
                        knowledgeList
                    } = this.$refs.baseRef.api_result();
                    const {applicableYear,labelList,areaList} = this.$refs.tagRef.api_result();;
                    question = {
                        ...question,
                        projectId:projectId.length?projectId[projectId.length-1]:'',
                        projectName,
                        subjectId,
                        subjectName,
                        chapterList,
                        questionDeveloperId,
                        questionDeveloperName,
                        knowledgeList,
                        applicableYear,
                        labelList: labelList ? labelList.filter(label => label.labelDetailId) : [],
                        areaList
                    };
                    const props = ['questionKeywords','questionScoreWeight'];
                    props.forEach((prop)=>{
                        if (question[prop] === '' || question[prop] === null || question[prop] === undefined){
                            delete question[prop];
                        }
                    });
                    return question;
                };
                const rcResourceQuestionPostVoList = questionList.map((question)=>{
                    question = getQuestion(question);
                    if (this.combinedType.includes(question.questionType)) {
                        let smallQuestionList = [];
                        question.smallQuestionList.forEach((smallQuestion) => {
                            smallQuestion = getQuestion(smallQuestion);
                            delete smallQuestion.smallQuestionList;
                            smallQuestionList.push(smallQuestion);
                        });
                        question.smallQuestionList = smallQuestionList;
                    } else {
                        delete  question.smallQuestionList;
                    }

                    return question;
                });
                const imgList = this.getImgList(rcResourceQuestionPostVoList);
                return questionApi.batchRepeatRewrite({
                    repeatQuestionPutVos: rcResourceQuestionPostVoList,
                    filePathList: Array.from(new Set(imgList)),
                    questionTypeList,
                    rewriteType: type.slice(0, 1).toUpperCase(),
                });
            },
		}
	};
</script>
<style lang="less" scoped>
	.edit-frame {
		padding: 0 10px;
        display: flex;
        height: 100%;
        max-height: 100%;
		/deep/ .el-button--text {
			color: #2e85ff;
			font-size: 14px;
		}
		.base,
		.tag,
		.question {
			padding: 10px 10px 0 10px;
			.top {
				display: flex;
				align-items: center;
			}
			.title {
				font-size: 14px;
				font-weight: bold;
				margin-right: 10px;
			}
		}
        .edit-input,.edit-preview{
            height: 100%;
            background-color: #fff;
            overflow-y: auto;
            box-sizing: border-box;
            padding-bottom: 30px;
            > .title {
                display: flex;
                align-items: center;
                height: 45px;
                line-height: 45px;
				font-size: 14px;
                font-weight: bold;
				border-bottom: 1px solid #d7d7d7;
                padding-left: 10px;
			}
            .title-icon{
                margin-right: 8px;
            }
        }
		.edit-input{
			flex: 1;
            padding-top: 0px;
		}
        .trans{
            width: 10px!important;
            flex-shrink: 0;
        }
		.edit-preview {
			width: 400px;
			flex-shrink: 0;
            .preview {
                padding: 10px
            }
		}
	}
</style>
